#include <vector>
#include "unit_locator.h"

using namespace std;

/**
 * Public constructor. Makes internal REFERENCE to game settings
 */
unit_locator::unit_locator(const game_settings& _settings):
	settings(_settings)
{
}

/**
 * Internal function for sorting available states by unit count
 */
bool cmp_available(const available& a, const available& b)
{
	return (a.unit_count > b.unit_count);
}

/**
 * TODO: rename zones
 * Decides where to locate available units among the allowed zones
 */
vector<location> unit_locator::locate_units(vector<available> units, const vector<zone>& zones)
{
	vector<zone> my_zones;

	for (unsigned i = 0; i < zones.size(); i++)
	{
		if (zones[i].player_num == settings.my_num)
		{
			my_zones.push_back(zones[i]);
		}
	}

	// Try to split units into equal move_interval groups
	while (units.size() < (unsigned) settings.move_interval && units.size() < my_zones.size())
	{
		sort(units.begin(), units.end(), cmp_available);

		if (units[0].unit_count == 1)
		{
			break;
		}

		available unit;
		unit.unit_type_id = units[0].unit_type_id;
		unit.unit_count = units[0].unit_count / 2;
		units.push_back(unit);
		units[0].unit_count -= unit.unit_count;
	}

	vector<location> locations;
	for (unsigned i = 0; i < units.size(); i++)
	{
		location loc;
		loc.x = my_zones[i].x;
		loc.y = my_zones[i].y;
		loc.unit_type_id = units[i].unit_type_id;
		loc.unit_count = units[i].unit_count;
		locations.push_back(loc);
	}

	return locations;
}